package com.kust.smarthome.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kust.smarthome.web.model.Room;
import com.kust.smarthome.web.model.User;
import com.kust.smarthome.web.service.IRoomService;
import com.kust.smarthome.web.service.IUserService;
import com.kust.smarthome.web.vo.RoomVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author iAuzre
 * @since 2021-07-14
 */
@RestController
@RequestMapping("/room")
@Api(value = "房间相关", tags = {"user-tag"})
public class RoomController {

    @Resource
    private IRoomService roomService;

    @Resource
    private IUserService userService;

    @GetMapping("")
    @ApiOperation("通过用户的登录信息获取用户房间信息")
    public List<Room> getRoomListByUser(Principal principal) {

        User user = userService.getByUsername(principal.getName());

        QueryWrapper<Room> query = new QueryWrapper<>();
        query.eq("user_id", user.getId());

        List<Room> list = roomService.list(query);

        return list;
    }

    @GetMapping("/add")
    public boolean addRoom(Principal principal, RoomVo roomVo) {

        User user = userService.getByUsername(principal.getName());

        Room room = new Room()
                .setUserId(user.getId())
                .setName(roomVo.getName())
                .setTypeId(roomVo.getTypeId());

        return roomService.save(room);
    }

    @DeleteMapping("/deleteById")
    public boolean deleteById(Principal principal, Integer id) {
        User user = userService.getByUsername(principal.getName());

        Room room = roomService.getById(id);

        if (user.getId() == room.getUserId()) {
            return roomService.removeById(id);
        }

        return false;
    }
}
